package com.sinosoft.weixin.utils;

import org.apache.commons.io.IOUtils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.security.MessageDigest;

public abstract class MessageDigestUtils {
	/**
	 * 计算字符串的 MD5 值，使用 UTF-8 编码
	 * @param str
	 * @return
	 */
	public static String getMD5(String str){
		if(null == str){
			return null;
		}
		
		try{
			MessageDigest md = MessageDigest.getInstance("md5");
			byte[] data = md.digest(str.getBytes("utf-8"));
			return ByteUtils.toHexString(data);
		}catch(Exception ex){
			throw new RuntimeException("MD5 计算失败！",ex);
		}
		
	}
	
	/**
	 * 计算文件的 MD5
	 * @param file
	 * @return
	 */
	public static String getFileMD5(File file){
		if(null == file){
			throw new NullPointerException();
		}
		if(!file.exists() || !file.isFile()){
			throw new IllegalArgumentException(file.getAbsolutePath() + " 不是一个合法的文件！");
		}
		
		BufferedInputStream fis = null;
		try{
			MessageDigest md = MessageDigest.getInstance("md5");
			byte[] buffer = new byte[1024];
			fis = new BufferedInputStream(new FileInputStream(file));
			int count = 0;
			while((count = fis.read(buffer)) > 0){
				md.update(buffer,0,count);
			}
			return ByteUtils.toHexString(md.digest());
		}catch(Exception ex){
			throw new RuntimeException("MD5 计算失败！",ex);
		}finally{
			IOUtils.closeQuietly(fis);
		}
	}
	
	public static String getSHA1(String str){
		if(null == str){
			return null;
		}
		
		try{
			MessageDigest md = MessageDigest.getInstance("sha1");
			byte[] data = md.digest(str.getBytes("utf-8"));
			return ByteUtils.toHexString(data);
		}catch(Exception ex){
			throw new RuntimeException("SHA1 计算失败！",ex);
		}
	}
	
	public static String getFileSHA1(File file){
		if(null == file){
			throw new NullPointerException();
		}
		if(!file.exists() || !file.isFile()){
			throw new IllegalArgumentException(file.getAbsolutePath() + " 不是一个合法的文件！");
		}
		
		BufferedInputStream fis = null;
		try{
			MessageDigest md = MessageDigest.getInstance("sha1");
			byte[] buffer = new byte[1024];
			fis = new BufferedInputStream(new FileInputStream(file));
			int count = 0;
			while((count = fis.read(buffer)) > 0){
				md.update(buffer,0,count);
			}
			return ByteUtils.toHexString(md.digest());
		}catch(Exception ex){
			throw new RuntimeException("SHA1 计算失败！",ex);
		}finally{
			IOUtils.closeQuietly(fis);
		}
	}
}
